const fs = require("fs");
const path = require("path");
const PDFDocument = require("pdfkit");
const pdfParse = require("pdf-parse");

exports.createFileWithPath = function (dirPath) {
  if (!fs.existsSync(dirPath)) {
    fs.mkdirSync(dirPath, { recursive: true });
  }
};

exports.genPdfFile = (outputPath, content) => {
  // 创建一个 PDF 文档对象
  const doc = new PDFDocument();
  doc.font(path.join(__dirname, "../fonts/simsun.ttf"));
  const { outline } = doc;
  content.forEach((element, idx) => {
    if (idx !== 0) {
      doc.addPage();
    }
    // 添加书签
    outline.addItem(element.name);
    doc.text(element.name, 120, 130);
    doc.moveDown();
    doc.text(element.content);
    doc.moveDown();
  });

  // 将 PDF 文档保存到本地文件
  doc.pipe(fs.createWriteStream(outputPath));
  doc.end();
};

exports.isPdfFile = (filePath) => {
  return filePath.endsWith(".pdf");
};

exports.readPdfFileText = async (filePath) => {
  const data = fs.readFileSync(filePath);
  const { text } = await pdfParse(data);
  return text;
};
